package com.dji.compose_learning.ui.view

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintSet

@Composable
fun DecoupledView() {
    Column {
        BoxWithConstraints {
            val constraints =
                if (maxWidth > maxHeight) { //这个maxwidth和maxheight是从BoxWithConstraints来的
                    decoupledConstraints(10.dp, 1)
                } else {
                    decoupledConstraints(16.dp, 0)
                }
            ConstraintLayout(modifier = Modifier.padding(16.dp), constraintSet = constraints) {
//            val (button, text) = createRefs()
                Button(onClick = { /*TODO*/ }, modifier = Modifier.layoutId("button")) {
                    Text(text = "Button")
                }

                Text(text = "this is a text", modifier = Modifier.layoutId("text"))
            }
        }
        Spacer(modifier = Modifier.height(20.dp))
        Row(modifier = Modifier
            .fillMaxWidth()
            .height(IntrinsicSize.Min) //这里设置高度为包含子元素的最小值
            .background(Color.Gray)) {
            Text(text = "Hi",
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 4.dp)
                    .wrapContentWidth(Alignment.Start))

            Spacer(modifier = Modifier
                .fillMaxHeight()
                .width(1.dp)
                .background(Color.Black))

            Text(text = "there",
                modifier = Modifier
                    .weight(1f)
                    .padding(end = 4.dp)
                    .wrapContentWidth(Alignment.End))
        }
    }
}

/**
 * 约束外移，实现约束和布局分离，可通过条件加载不同的约束
 */
private fun decoupledConstraints(margin: Dp, direction: Int): ConstraintSet {
    return ConstraintSet {
        val button = createRefFor("button")
        val text = createRefFor("text")

        if (direction == 0) { //竖屏
            constrain(button) {
                top.linkTo(parent.top, margin)
            }

            constrain(text) {
                top.linkTo(button.bottom, margin)
            }
        } else { //横屏
            constrain(button) {
                top.linkTo(parent.top, margin)
            }
            constrain(text) {
                top.linkTo(parent.top, margin)
                start.linkTo(button.end, margin)
            }
        }

    }
}






















